<?php
namespace api\models;

use Yii;
use common\models\VoteLog as BaseVoteLog;
use api\helpers\JWT;
use api\models\Vote;
use api\models\VotePlayer;
use api\models\Category;
use common\helpers\Util;


class VoteLog extends BaseVoteLog
{
    public $token;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        $reles = parent::rules();
        $reles[] = ['token', 'string'];
        $reles[] = ['cid', 'string'];
        return $reles;
    }
    
    /** @inheritdoc */
    public function beforeValidate()
    {
        // 验证投票时间是否开始
        $this->validateTime();

        $token = JWT::decode($this->token);
        $this->openid = $token['openid'];
        $this->nickname = $token['nickname'];

        if (!$this->openid || !$this->nickname) {
            Util::error('授权问题', 502);
        }
        $this->num = 1;
        $this->created_at = time();

        // 验证间隔
        $this->validateIpNums();

        // 验证作品是否是10个
        $this->validateNum($this->vid);


        //验证一个用户一天只能投一次
        $this->validateIp(); 

        if (parent::beforeValidate()) {
            $vids = explode(',', $this->vid);
            foreach ($vids as $key => $val) {
                $vids[$key] = trim(explode('_', $val)[1]);
            }
            return VotePlayer::updateAllCounters(['votes' => '1'], ['id' => $vids]);
        } else {
            return false;
        }
    }

    // 验证同个IP的投票间隔
    public function validateIpNums() {
        $ip = Yii::$app->request->headers->get('x-real-ip');
        $cache = Yii::$app->cache;
        $data = $cache->get($ip);
        if ($data === false) {
            $cache->set($ip, $ip, 10);
            return true;
        }
        throw new \yii\web\HttpException(500, '投票间隔太少'); 
    }


    // 验证选择个数
    public function validateNum ($vid)
    {
        $vids = explode(',', $vid);
        $map = [];
        foreach ($vids as $item) {
            $group_id = trim(explode('_', $item)[0]);
            $map[$group_id][] = trim($item);
        }

        $category = Category::find()->where(['vid' => Yii::$app->request->post('cid')])->all();

        foreach ($category as $citem) {

            if (!isset($map[$citem->id])) {
                throw new \yii\web\HttpException(500, $citem->title . '必须选择'); 
            }

            if (count($map[$citem->id]) !== $citem->num) {
                throw new \yii\web\HttpException(500, $citem->title . '必须选择' . $citem->num . '个选手'); 
            }
        }

        return true;
        
    }

    // 验证是否投过票
    public function validateIp() {
        $log = $this->find()
            ->where(['openid' => $this->openid, 'cid' => $this->cid])
            ->orderBy('id desc')
            ->asArray()
            ->one();

        if ($log === null) return true;

        if(date('Y-d-m', $log['created_at']) == date('Y-d-m', time())){
            throw new \yii\web\HttpException(500, '您已经投过票了，请明天再来'); 
        }

    }

    //验证开始时间
    //0 为没有开始 -1 为已结束 1为正常时间
    public function validateTime()
    {
        $model = Vote::findOne($this->cid);

        if(time() < $model->time_start) {
            throw new \yii\web\HttpException(500, '投票还没开始，开始时间' . date('Y-m-d H:i:s', $model->time_start));
        }

        if(time() > $model->time_end) {
            throw new \yii\web\HttpException(500, '投票已经结束，结束时间' . date('Y-m-d H:i:s', $model->time_end));
        }

    }
}
